<template>
  <view class="webview-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image class="back-icon" src="/static/Images/shop/Fanhui.png" mode="aspectFit"></image>
      </view>
      <view class="title">{{ pageTitle }}</view>
    </view>

    <!-- 二维码显示界面 (微信环境) -->
    <view v-if="showQRCode" class="qrcode-container">
      <view class="qrcode-content">
        <view class="qrcode-title">{{ qrCodeTitle }}</view>
        <view class="qrcode-subtitle">{{ qrCodeSubtitle }}</view>
        
        <view class="qrcode-wrapper">
          <image 
            :src="qrCodeUrl"
            id="qrcode-img"
            class="qrcode-image"
            mode="aspectFit"
            :style="{ width: qrCodeSize + 'rpx', height: qrCodeSize + 'rpx' }"
            @error="onQRCodeError"
            @load="onQRCodeLoad"
          />
        </view>
        
        <view class="qrcode-tips">
          <view class="tip-item">
            <text class="tip-number">1</text>
            <text class="tip-text">打开支付宝APP</text>
          </view>
          <view class="tip-item">
            <text class="tip-number">2</text>
            <text class="tip-text">扫描上方二维码</text>
          </view>
          <view class="tip-item">
            <text class="tip-number">3</text>
            <text class="tip-text">完成刷脸认证</text>
          </view>
        </view>
        
        <view class="qrcode-actions">
          <button class="refresh-btn" @click="refreshQRCode">已完成人脸核身</button>
        </view>
      </view>
    </view>

    <!-- H5环境引导界面 -->
    <view v-if="showH5Guide" class="h5-guide-container">
      <view class="h5-guide-content">
        <view class="guide-icon">
           <image class="alipay-icon" src="/static/Images/common/alipay-icon.svg" mode="aspectFit"></image>
         </view>
        
        <view class="guide-title">需要在支付宝中完成认证</view>
        <view class="guide-subtitle">点击下方按钮将自动跳转到支付宝APP进行刷脸认证</view>
        
        <view class="guide-steps">
          <view class="step-item">
            <text class="step-number">1</text>
            <text class="step-text">点击"打开支付宝"按钮</text>
          </view>
          <view class="step-item">
            <text class="step-number">2</text>
            <text class="step-text">在支付宝中完成刷脸认证</text>
          </view>
          <view class="step-item">
            <text class="step-number">3</text>
            <text class="step-text">认证完成后返回本页面</text>
          </view>
        </view>
        
        <view class="guide-actions">
          <button v-if="!hasClickedAlipay" class="open-alipay-btn" @click="openInAlipay">打开支付宝</button>
          <button v-else class="check-result-btn" @click="checkAuthResult">已完成人脸核身</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import QRCode from 'qrcode';
import api from '@/utils/api';
import { userStorage } from '@/utils/storage';

// 页面标题
const pageTitle = ref('加载中...');
// webview URL
const webUrl = ref('');
// 二维码尺寸
const qrCodeSize = ref(400);
// 二维码URL
const qrCodeUrl = ref('');
// 二维码标题和副标题
const qrCodeTitle = ref('请使用支付宝扫码刷脸认证');
const qrCodeSubtitle = ref('请使用支付宝扫描下方二维码进行刷脸认证');

// 环境检测相关
const isWechat = ref(false);
const isMiniProgram = ref(false);
const isH5 = ref(false);
const showQRCode = ref(false);
const showH5Guide = ref(false);
const hasClickedAlipay = ref(false);

// 检测运行环境
const detectEnvironment = () => {
  console.log('=== 开始环境检测 ===');
  
  // 检测是否为uni-app环境
  // #ifdef MP-WEIXIN
  console.log('检测到微信小程序环境');
  isMiniProgram.value = true;
  isWechat.value = true;
  showQRCode.value = true;
  // #endif
  
  // #ifdef H5
  console.log('检测到H5环境');
  isH5.value = true;
  
  // 在H5环境下进一步检测是否为微信浏览器
  const userAgent = navigator.userAgent.toLowerCase();
  console.log('UserAgent:', userAgent);
  
  if (userAgent.includes('micromessenger')) {
    console.log('检测到微信浏览器环境');
    isWechat.value = true;
    showQRCode.value = true;
  } else {
    console.log('检测到普通H5浏览器环境');
    showH5Guide.value = true;
  }
  // #endif
  
  console.log('环境检测结果:', {
    isWechat: isWechat.value,
    isMiniProgram: isMiniProgram.value,
    isH5: isH5.value,
    showQRCode: showQRCode.value,
    showH5Guide: showH5Guide.value
  });
};

// 生成二维码
const generateQRCode = async () => {
  try {
    console.log('开始生成二维码，URL:', webUrl.value);
    
    if (!webUrl.value) {
      console.error('二维码生成失败：URL为空');
      uni.showToast({
        title: 'URL为空，无法生成二维码',
        icon: 'none'
      });
      return;
    }
    
    // 确保URL是字符串类型
    const urlString = String(webUrl.value);
    console.log('URL类型检查:', typeof urlString, urlString);
    
    // 计算实际尺寸（rpx转px）
    const actualSize = qrCodeSize.value / 2;
    console.log('二维码尺寸:', actualSize);
    
    // 生成二维码数据URL
    const qrDataURL = await QRCode.toDataURL(urlString, {
      width: actualSize,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    });
    
    console.log('二维码数据URL生成成功，长度:', qrDataURL.length);
    
    // 设置二维码URL到响应式变量，uni-app会自动更新image元素
    qrCodeUrl.value = qrDataURL;
    console.log('二维码URL已设置到响应式变量');
    
  } catch (error) {
    console.error('生成二维码失败:', error);
    uni.showToast({
      title: '二维码生成失败: ' + error.message,
      icon: 'none'
    });
  }
};

// 查询认证状态的通用方法
const queryAuthStatus = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '查询认证状态中...'
    });
    
    // 获取用户token
    const token = userStorage.getToken();
    console.log('获取到的token:', token);
    
    if (!token) {
      uni.hideLoading();
      uni.showModal({
        title: '提示',
        content: '用户未登录，请先登录',
        showCancel: false,
        confirmText: '确定',
        success: () => {
          uni.reLaunch({ url: '/pages/login/login' });
        }
      });
      return;
    }
    
    // 调用queryReal接口
    const response = await api.queryReal(token);
    uni.hideLoading();
    
    // 显示接口返回的msg内容
    uni.showModal({
      title: '认证状态',
      content: response.msg || '查询完成',
      showCancel: false,
      confirmText: '确定',
      success: () => {
        // 点击确定返回个人中心
        uni.reLaunch({ url: '/pages/users/index' });
      }
    });
    
  } catch (error) {
    uni.hideLoading();
    console.error('查询认证状态失败:', error);
    
    // 显示错误信息
    uni.showModal({
      title: '查询失败',
      content: error.message || '网络错误，请稍后重试',
      showCancel: false,
      confirmText: '确定'
    });
  }
};

// 刷新二维码
const refreshQRCode = () => {
  // 调用查询认证状态方法
  queryAuthStatus();
};

// H5环境下唤醒支付宝APP
const openInAlipay = () => {
  console.log('尝试唤醒支付宝APP，URL:', webUrl.value);
  
  if (!webUrl.value) {
    uni.showToast({
      title: 'URL为空，无法打开',
      icon: 'none'
    });
    return;
  }
  
  // 设置已点击状态
  hasClickedAlipay.value = true;
  
  // 构造支付宝唤醒链接
  const alipayScheme = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(webUrl.value)}`;
  
  console.log('支付宝唤醒链接:', alipayScheme);
  
  // 尝试唤醒支付宝APP
  window.location.href = alipayScheme;
  
  // 设置超时检测，如果没有成功唤醒则提示用户
  setTimeout(() => {
    uni.showModal({
      title: '提示',
      content: '如果没有自动打开支付宝，请手动复制链接到支付宝中打开',
      showCancel: true,
      cancelText: '取消',
      confirmText: '复制链接',
      success: (res) => {
        if (res.confirm) {
          // 复制原始链接到剪贴板
          // #ifdef H5
          if (navigator.clipboard) {
            navigator.clipboard.writeText(webUrl.value).then(() => {
              uni.showToast({
                title: '链接已复制',
                icon: 'success'
              });
            }).catch(() => {
              uni.showToast({
                title: '复制失败，请手动复制',
                icon: 'none'
              });
            });
          } else {
            uni.showToast({
              title: '浏览器不支持自动复制',
              icon: 'none'
            });
          }
          // #endif
        }
      }
    });
  }, 2000);
};

// 检查认证结果
const checkAuthResult = () => {
  // 调用查询认证状态方法
  queryAuthStatus();
};

// 二维码图片加载成功
const onQRCodeLoad = () => {
  console.log('二维码图片加载完成');
};

// 二维码图片加载失败
const onQRCodeError = (error) => {
  console.error('二维码图片加载失败:', error);
  uni.showToast({
    title: '二维码图片显示失败',
    icon: 'none'
  });
};

// 获取URL参数
onMounted(() => {
  console.log('=== onMounted 开始执行 ===');
  
  // 优先从sessionStorage获取URL，如果没有则从URL参数获取（兼容旧版本）
  let targetUrl = uni.getStorageSync('webview_url');
  console.log('从sessionStorage获取的URL:', targetUrl);
  
  if (!targetUrl) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    console.log('页面参数options:', options);
    
    if (options.url) {
      targetUrl = decodeURIComponent(options.url);
      console.log('从URL参数获取的URL:', targetUrl);
    }
  } else {
    // 使用完后清除存储，避免数据残留
    uni.removeStorageSync('webview_url');
    console.log('已清除sessionStorage中的URL');
  }
  
  console.log('最终获取的targetUrl:', targetUrl);
  
  if (targetUrl) {
    webUrl.value = targetUrl;
    
    // 进行环境检测
    detectEnvironment();
    
    // 根据环境设置页面标题
    if (showQRCode.value) {
      pageTitle.value = '扫码刷脸认证';
      // 延迟生成二维码，确保DOM已渲染
      setTimeout(() => {
        generateQRCode();
      }, 500);
    } else if (showH5Guide.value) {
      pageTitle.value = '打开支付宝认证';
    }
    
  } else {
    uni.showToast({
      title: '缺少URL参数',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss">
.webview-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 导航栏 */
.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  background-color: #ffffff;
  padding-top: var(--status-bar-height, 44px);
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

/* 二维码容器 */
.qrcode-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background-color: #f8f9fa;
}

.qrcode-content {
  width: 100%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;
}

.qrcode-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 20rpx;
}

.qrcode-subtitle {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 60rpx;
  line-height: 1.5;
}



.qrcode-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 60rpx;
  padding: 40rpx;
  background-color: #ffffff;
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
}

.qrcode-image {
  border-radius: 8rpx;
  display: block;
}

.qrcode-tips {
  margin-bottom: 60rpx;
}

.tip-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 24rpx;
  padding: 0 20rpx;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  background-color: #1890ff;
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 600;
  border-radius: 50%;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.tip-text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.4;
}

.qrcode-actions {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.refresh-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1890ff;
  color: #ffffff;
}

.refresh-btn:active {
  background-color: #1677cc;
}

/* H5引导界面样式 */
.h5-guide-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background-color: #f8f9fa;
}

.h5-guide-content {
  width: 100%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;
}

.guide-icon {
  margin-bottom: 40rpx;
}

.alipay-icon {
  width: 120rpx;
  height: 120rpx;
}

.guide-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 20rpx;
}

.guide-subtitle {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 60rpx;
  line-height: 1.5;
}

.guide-steps {
  margin-bottom: 60rpx;
}

.step-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 24rpx;
  padding: 0 20rpx;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  background-color: #1890ff;
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 600;
  border-radius: 50%;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.step-text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.4;
}

.guide-actions {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.open-alipay-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1890ff;
  color: #ffffff;
}

.open-alipay-btn:active {
  background-color: #1677cc;
}

.check-result-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #52c41a;
  color: #ffffff;
}

.check-result-btn:active {
  background-color: #389e0d;
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .qrcode-content {
    padding: 40rpx 30rpx;
  }
  
  .qrcode-title {
    font-size: 32rpx;
  }
  
  .qrcode-subtitle {
    font-size: 26rpx;
  }
  
  .tip-text {
    font-size: 26rpx;
  }
}
</style>